from flask import Flask
from flask import request
import json

from core.db.mongo_pool import MongoPool
import settings


class ProxyAPI(object):

    def __init__(self):
        self.app = Flask(__name__)
        self.mongo_pool = MongoPool()

        @self.app.route('/random')
        def random():
            """
            实现随机获取一个代理IP的服务
            可用通过 protocol 和 domain 参数对IP进行过滤
            protocol: 当前请求的协议类型
            domain: 当前请求域名
            :return:
            """
            protocol = request.args.get('protocol')
            domain = request.args.get('domain')
            print(protocol)
            proxy = self.mongo_pool.random_proxy(protocol=protocol, domain=domain, count=settings.RANDOM_PROXY_COUNT)

            try:
                if protocol:
                    return "{}://{}:{}".format(protocol, proxy.ip, proxy.port)
                else:
                    return "{}:{}".format(proxy.ip, proxy.port)
            except Exception:
                return proxy

        @self.app.route('/protocol')
        def protocol():
            """
            实现查询所有的可用代理IP的服务
            可用通过 protocol 和 domain 参数对IP进行过滤
            :return:
            """
            protocol = request.args.get('protocol')
            domain = request.args.get('domain')
            proxies = self.mongo_pool.get_proxies(protocol=protocol, domain=domain)
            li = []
            for proxy in proxies:
                li.append(proxy.__dict__)
            return json.dumps(li)

        @self.app.route('/disable_domain')
        def disable_domain():
            ip = request.args.get('ip')
            domain = request.args.get('domain')

            if ip is None:
                return '请传入ip参数'
            if domain is None:
                return '请传入domain参数'

            # 更新域名成功
            self.mongo_pool.disable_domain(ip=ip, domain=domain)
            return '该ip添加不可用域名成功'

    def run(self):
        self.app.run('0.0.0.0', port=5000)

    @classmethod
    def start(cls):
        cls().run()

if __name__ == '__main__':
    ProxyAPI().run()
    # ProxyAPI.start()